#include "Server.h"
#include <iostream>

Server::Server(boost::asio::io_context& ioc, int port)
    : ioc(ioc)
    , act(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
    start_accept();
}

void Server::start_accept()
{
    try {
        Session* s = new Session(ioc);
        act.async_accept(s->get_socket(), std::bind(&Server::accept_handle, this, s, std::placeholders::_1));
    } catch (boost::system::system_error& e) {
        std::cout << e.what() << std::endl;
    }
}

void Server::accept_handle(Session* s, const boost::system::error_code& error)
{
    if (!error) {
        s->Start();
    } else {
        delete s;
    }
    start_accept();
}
